package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author 徐梦轲
 * @create 2022-06-25 17:18
 */
public class TcpServer {
    ServerSocket listenSocket = null;
    private int port;

    public TcpServer(int port) throws IOException {
        listenSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true) {
            //建立连接
            Socket clientSocket = listenSocket.accept();
            Thread thread = new Thread()  {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.start();
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        String log = String.format("[ %s: %d] 客户端上线",
                clientSocket.getInetAddress(),clientSocket.getPort());
        System.out.println(log);
        try (InputStream is = clientSocket.getInputStream()) {
            try (OutputStream os = clientSocket.getOutputStream()) {
                while (true) {
                    Scanner sc = new Scanner(is);
                    if (!sc.hasNext()) {
                        log = String.format("[ %s: %d] 客户端下线",
                                clientSocket.getInetAddress(),clientSocket.getPort());
                        System.out.println(log);
                        break;
                    }
                    String request = sc.next();
                    String respone = process(request);
                    PrintWriter writer = new PrintWriter(os);
                    writer.println(respone);
                    writer.flush();
                    log = String.format("[ %s: %d] request: response: ",
                            clientSocket.getInetAddress(),clientSocket.getPort(),request,respone);
                    System.out.println(log);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpServer server = new TcpServer(9090);
        server.start();
    }
}
